package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.dto.msg.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constants.RedisConstants;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author zjr
 * @since 2024-12-30
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LikedRecordRedisServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private final RabbitMqHelper rabbitMqHelper;
    private final StringRedisTemplate redisTemplate;

    @Override
    public void addLikeRecord(LikeRecordFormDTO dto) {
        // 1. 获取当前登录用户
        Long userId = UserContext.getUser();
        // 2. 判断是否点赞 dto.liked为true则是点赞
        boolean flag = dto.getLiked() ? liked(dto, userId) : unliked(dto, userId);
        if(!flag) {  // 说明点赞或取消赞失败（之前已经点过赞）
            return;
        }
        // 3. 基于Redis统计该业务下的总点赞量  likes:set:biz:评论id
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + dto.getBizId();
        Long totalLikesNum = redisTemplate.opsForSet().size(key);
        if(totalLikesNum == null){
            return;
        }
        // 4. 采用zset结构缓存点赞的总数  likes:times:type:QA  likes:times:type:NOTE
        String bizTypeTotalLikeKey = RedisConstants.LIKES_TIMES_KEY_PREFIX + dto.getBizType();
        log.debug("写入点赞总数到zset 业务类型{} 点赞总数{}", bizTypeTotalLikeKey, totalLikesNum);
        redisTemplate.opsForZSet().add(bizTypeTotalLikeKey, dto.getBizId().toString(), totalLikesNum);
    }

    /**
     * 批量查询点赞的状态
     * @param bizIds
     * @return 已点赞的bizIds集合
     */
    @Override
    public Set<Long> getLikesStatusByBizIds(List<Long> bizIds) {
        // 1. 获取当前登录用户
        Long userId = UserContext.getUser();
//        if(CollUtils.isEmpty(bizIds)){
//            return CollUtils.emptySet();
//        }
//        Set<Long> likedBizIds = new HashSet<>();
//        for (Long bizId : bizIds) {
//            String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + bizId;
//            // 判断该业务id 的点赞用户集合中是否包含当前用户
//            Boolean isMember = redisTemplate.opsForSet().isMember(key, userId.toString());
//            if(isMember){
//                likedBizIds.add(bizId);
//            }
//        }
//        return likedBizIds;
        // 基于管道对批量操作的改进
        // 2. 查询点赞状态
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + bizId;
                src.sIsMember(key, userId.toString());
            }
            return null;
        });
        // 3. 返回结果
        return IntStream.range(0, objects.size()) // 创建从0到size的流
                .filter(i -> (boolean) objects.get(i)) // 遍历每个元素，保留结果为true的i
                .mapToObj(bizIds::get)  // 用角标i取bizIds中对应的数据，就是点赞过的id
                .collect(Collectors.toSet()); // 收集
    }

    /**
     * 将redis中 业务类型下面 某业务的点赞总数 发送消息到MQ
     * @param bizType 业务类型
     * @param maxBizSize 业务点赞数量
     */
    @Override
    public void readLikedTimesAndSendMessage(String bizType, int maxBizSize) {
        // 1. 拼接key  likes:times:type:QA  likes:times:type:NOTE
        String bizTypeTotalLikeKey = RedisConstants.LIKES_TIMES_KEY_PREFIX + bizType;

        // 2. 从redis的zset中  按分数排序取 maxBizSize 的业务点赞信息  popmin(获取并移除)
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().popMin(bizTypeTotalLikeKey, maxBizSize);
        if(CollUtils.isEmpty(typedTuples)){
            return;
        }
        List<LikedTimesDTO> msgList = new ArrayList<>();
        // 3. 封装LikedTimesDTO 消息类型
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String bizId = typedTuple.getValue();       // 业务id
            Double likedTimes = typedTuple.getScore();  // 点赞数
            if(bizId == null || likedTimes == null) {
                continue;
            }
            log.debug("bizId {}, likedTimes:{}", bizId, likedTimes);
            LikedTimesDTO msg = LikedTimesDTO.of(Long.valueOf(bizId), likedTimes.intValue());
            msgList.add(msg);
        }
        // 4. 发送消息到MQ
        String routingKey = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, bizType);
        log.debug("批量发送点赞消息 消息内容{}", msgList);
        rabbitMqHelper.send(
                MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                routingKey,
                msgList);
    }

    /**
     * 基于Redis取消赞
     * @param dto
     * @return
     */
    private boolean unliked(LikeRecordFormDTO dto, Long userId) {
        // 拼接key
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + dto.getBizId();
        // 从set结构中删除 当前userId
        Long result = redisTemplate.opsForSet().remove(key, userId.toString());
        return result != null && result > 0;  // 取消点赞是否成功
    }

    /**
     * 基于Redis点赞
     * @param dto
     * @return
     */
    private boolean liked(LikeRecordFormDTO dto, Long userId) {
        // 拼接key
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + dto.getBizId();
        // redisTemplate 往redis的set结构添加点赞记录
        Long result = redisTemplate.opsForSet().add(key, userId.toString());
        return result != null && result > 0;  // 点赞是否成功
    }
}
